import {useIndexStore, useSeniorSearchStore} from "@/store";
import {
  Button,
  Checkbox,
  DialogInstance,
  DialogPlugin,
  Form,
  FormItem,
  Option,
  Select,
  Textarea
} from "tdesign-vue-next";
import MessageUtil from "@/utils/model/MessageUtil";
import {IndexItem} from "$/elasticsearch-client";

interface Config {
  index: string;
  query: string;
  script: string;
  async: boolean;
}

/**
 * 索引迁移，从一个索引转到另一个索引
 * @param index
 */
export function indexReindex(index: string) {
  // 全部的索引
  const indices: Array<IndexItem> = useIndexStore().indices;
  const config = ref<Config>({
    index: '',
    query: '',
    script: '',
    async: false
  });

  let modalReturn = DialogPlugin({
    // TODO: 此处bete
    header: `索引【${index}】迁移（beta）`,
    placement: "center",
    draggable: true,
    default: () => <>
      <div style="margin-bottom: 7px;">
        如果 Mapping 中字段已经定义就不能修改其字段的类型等属性了，同时也不能改变分片的数量，
        可以使用 Reindex API 来解决这个问题。
      </div>
      <Form data={config.value} layout="vertical">
        <FormItem label="目标索引 (Destination Index):" labelAlign={'top'}>
          <Select v-model={config.value.index} filterable clearable>
            {indices.map(item =>
              <Option key={item.name} value={item.name}
                      disabled={item.name === index}>{item.name}</Option>)}
          </Select>
        </FormItem>
        <FormItem label="查询过滤 (可选, JSON格式):" labelAlign={'top'}>
          <Textarea v-model={config.value.query} autosize={{minRows: 3, maxRows: 5}}
                    placeholder='{ "term": { "status": "published" } }'/>
        </FormItem>
        <FormItem label="脚本 (可选, 用于文档转换):" labelAlign={'top'}>
          <Textarea v-model={config.value.script} autosize={{minRows: 3, maxRows: 5}}
                    placeholder='ctx._source.new_field = ctx._source.old_field;'/>
        </FormItem>
        <FormItem labelAlign={'top'}>
          <Checkbox v-model={config.value.async}>是否异步执行 (推荐大数据量时勾选)</Checkbox>
        </FormItem>
      </Form>
    </>,
    footer: () => <>
      <Button variant="text" theme={'primary'}
              onClick={() => jumpTo(index, config, modalReturn)}>跳转到高级查询</Button>
      <Button onClick={() => modalReturn.destroy()}>取消</Button>
      <Button theme={'primary'} onClick={() => onOk(index, config, modalReturn)}>执行</Button>
    </>,
  });
}

function jumpTo(index: string, config: Ref<Config>, modalReturn: DialogInstance) {
  useSeniorSearchStore().loadEvent({
    method: 'POST',
    link: '_reindex' + (config.value.async ? '?wait_for_completion=false' : ''),
    body: `{
    "source": {"index": "${index}",
    "dest": {"index": "${config.value.index}"}
}`
  });
  modalReturn.destroy();
}

function onOk(index: string, config: Ref<Config>, modalReturn: DialogInstance) {
  if (config.value.index == '') {
    MessageUtil.warning("请选择目标索引");
    return;
  }
  modalReturn.destroy();
  console.log("开始迁移：", index, config.value);
  // useLoadingStore().start("开始进行索引迁移");
  // fetchEs<string>({
  //   url: '_reindex' + (config.value.async ? '?wait_for_completion=false' : ''),
  //   method: 'POST',
  //   data: {
  //     source: {index: index},
  //     dest: {index: config.value.index}
  //   },
  //   responseType: 'text'
  // }).then(res => MessageUtil.success(res))
  //   .catch(e => MessageUtil.error("迁移失败", e))
  //   .finally(() => {
  //     useLoadingStore().close();
  //     modalReturn.destroy();
  //   })
}
